package com.cqxyd.smartsite.controller.vs1;

import com.cqxyd.smartsite.pojo.CraneRecord;
import com.cqxyd.smartsite.pojo.EnvRecord;
import com.cqxyd.smartsite.pojo.Heartbeat;
import com.cqxyd.smartsite.service.DeviceInfoService;
import com.cqxyd.smartsite.service.ProgramInfoService;
import com.cqxyd.smartsite.service.UploadRecordService;
import com.cqxyd.smartsite.util.JSONResult;
import com.cqxyd.smartsite.util.PostHelper;
import com.cqxyd.smartsite.version.ApiVersion;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@ApiVersion(1)
@RequestMapping(value = "{version}/api/crane")
@Api(value = "塔吊监控信息接口", tags = "塔吊监控信息接口")
public class CraneRecordController1 {
    private final Logger logger = LoggerFactory.getLogger(CraneRecordController1.class);
    @Autowired
    private PostHelper postHelper;
    @Autowired
    private UploadRecordService uploadRecordService;
    @Autowired
    private ProgramInfoService programInfoService;
    @Autowired
    private DeviceInfoService deviceInfoService;

    @PostMapping(value = "record")
    @ApiOperation(value = "上传塔吊实时数据", notes = "工况数据上传（实时数据上传）", produces = "application/json")
    @ApiImplicitParams
            ({
                    @ApiImplicitParam(name = "registNo", value = "塔机编号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "serialNo", value = "主机（黑匣子）编号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "recordTime", value = "采集时间（yyyy-MM-dd HH:mm:ss）", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "height", value = "高度(m)", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "radius", value = "幅度", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "angle", value = "回转", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "load", value = "起重量数据(吨)", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "windSpeed", value = "风速（m/s）", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "obliquity", value = "倾角数据", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "loadPercentage", value = "重量百分比", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "percent", value = "力矩百分比", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "dirAngle", value = "倾斜方向，角度表示", required = false, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "fall", value = "吊绳倍率", required = false, dataType = "int", paramType = "query"),
                    @ApiImplicitParam(name = "status", value = "状态, 0：正常 1：预警 2：报警 3：违章 4：其他", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "message", value = "预警/报警/违章消息，非正常状态时必须传入", required = false, paramType = "query", dataType = "String")
            })
    public JSONResult<String> postElevator(@PathVariable("version") String version, String registNo, String serialNo, String recordTime, Double height,
                                           Double radius, Double angle, Double load, Double windSpeed, Double loadPercentage, Double percent, Double obliquity,
                                           Double dirAngle, Integer fall, String status, String message) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            List<String> keyAndSecret = programInfoService.getKeyAndSecret(serialNo);
            if (keyAndSecret == null) {
                return JSONResult.errorMsg("设备未注册，获取项目信息失败");
            }
            if (!"0".equals(status) && StringUtils.isEmpty(message)) {
                return JSONResult.errorMsg("预警/报警/违章消息，非正常状态时必须传入");
            }
            double safeLoad = 0d;
            if (loadPercentage != 0) {
                //重量百分比 等于 吊重/安全吊重
                safeLoad = load / loadPercentage;
            }
            Date realRecordTime = sdf.parse(recordTime);
            List<CraneRecord> list = new ArrayList<>();
            CraneRecord record = new CraneRecord();
            record.setRegistNo(registNo);
            record.setSerialNo(serialNo);
            record.setRecordTime(realRecordTime);
            record.setHeight(height);
            record.setRadius(radius);
            record.setAngle(angle);
            record.setLoad(load);
            record.setSafeLoad(safeLoad);
            record.setWindSpeed(windSpeed);
            record.setPercent(percent);
            record.setObliquity(obliquity);
            record.setDirAngle(dirAngle);
            record.setFall(fall);
            record.setStatus(status);
            record.setMessage(message);

            int recordId = uploadRecordService.insertAndGetId(serialNo, realRecordTime, record.toString(), "塔吊信息");
            if (recordId == 0) {
                String errorInfo = "保存塔吊信息上传记录出错：" + record.toString();
                logger.error(errorInfo);
                return JSONResult.errorMsg(errorInfo);
            } else {
                record.setSourceId(String.valueOf(recordId));
            }
            list.add(record);
            return postHelper.postCraneRecord(keyAndSecret.get(0), keyAndSecret.get(1), list);
        } catch (ParseException e) {
            e.printStackTrace();
            return JSONResult.errorMsg("时间转换异常，请确认格式为：yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return JSONResult.errorMsg("上传塔吊信息失败:" + e.getMessage());
        }
    }

    @PostMapping(value = "heartbeat")
    @ApiOperation(value = "上传塔吊心跳信息", notes = "心跳固定每10秒上传一次，平台校验与上次收到心跳的时间差，如果小于10s,则视为此次数据无效，如果大于等于10s则将设备在线时间加10s并更新最新心跳时间为此次收到心跳的时间。", produces = "application/json")
    @ApiImplicitParams
            ({
                    @ApiImplicitParam(name = "registNo", value = "塔机编号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "serialNo", value = "主机（黑匣子）编号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "recordTime", value = "采集时间（yyyy-MM-dd HH:mm:ss）", required = true, paramType = "query", dataType = "String")
            })
    public JSONResult<String> postHeartbeat(@PathVariable("version") String version, String registNo, String serialNo, String recordTime) {
        List<String> keyAndSecret = programInfoService.getKeyAndSecret(serialNo);
        if (keyAndSecret == null) {
            return JSONResult.errorMsg("设备未注册，获取项目信息失败");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date realRecordTime = sdf.parse(recordTime);
            Heartbeat heartbeat = new Heartbeat();
            heartbeat.setRegistNo(registNo);
            heartbeat.setSerialNo(serialNo);
            heartbeat.setSendTime(realRecordTime);

            try {
                //int affectRowCount = uploadRecordService.insert(serialNo, realRecordTime, heartbeat.toString(), "塔吊心跳信息");

                int affectRowCount =  deviceInfoService.updateLastHeartbeatTime(serialNo,realRecordTime);
                if (affectRowCount == 0) {
                    logger.error("更新设备最后心跳时间出错：" + serialNo);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return postHelper.postCraneHeartbeat(keyAndSecret.get(0), keyAndSecret.get(1), heartbeat);
        } catch (ParseException e) {
            e.printStackTrace();
            return JSONResult.errorMsg("时间转换异常，请确认格式为：yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return JSONResult.errorMsg("上传塔吊心跳失败:" + e.getMessage());
        }
    }
}
